#include <stdio.h>
#include <signal.h>
#include <setjmp.h>
#include <stdbool.h>
#include <malloc.h>
#include <stdlib.h>

#include "app.h"
#include "interaction.h"
#include "log.h"

#define UNUSED(x) (void)x

static jmp_buf buf;
static void deal_ctrl_c(int sig);

/**
 * @brief   主函数
 */
int main(int argc, char* argv[])
{
    UNUSED(argc);
    UNUSED(argv);

    int ret, ctrl_ret;
    func_t *init_ret;

    signal(SIGINT, deal_ctrl_c);

    func_t p_func[OPTION_NUM];
    struct app *app = (struct app *)malloc(sizeof(struct app));
    if (!app) {
        DEBUG("MALLOC ERROR!");
        return MALLOC_ERROR;
    }

    init_ret = init(app, p_func);
    if (init_ret == NULL) {
        DEBUG("INIT ERROR!");
        return 0;
    }

    ctrl_ret = setjmp(buf);
    if (ctrl_ret != true) {
    	ret = run(app, p_func);
        if (ret != true) {
            DEBUG("RUN ERROR!");
            return 0;
        }
    }

    ret = destroy(app);
    if (ret != true) {
        DEBUG("DESTROY ERROR!");
        return 0;
    }
    return 0;
}

/**
 * @brief   按下Ctrl+c时触发信号函数
 */
static void deal_ctrl_c(int sig)
{
    system("clear");
    longjmp(buf, 1);
}